import Global from "./Global";
const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Label)
    timeLabel: cc.Label = null;

    @property(cc.Label)
    label: cc.Label = null;

    timer: number = 0;
    isDisable: boolean = false;  //防止开始帧同步之后重复进入游戏场景
    matchTime: number = 0;

    onLoad() {
        this.enterMatching();
    }

    start() {

        //接收帧同步，需要进入游戏场景之前接收帧同步，不然会同步失败
        // Global.room.onRecvFrame = (event: MGOBE.types.BroadcastEvent<MGOBE.types.RecvFrameBst>) => {
        //     // let frame: MGOBE.types.Frame = event.data.frame;
        //     // let frameRate = Global.room.roomInfo.frameRate;
        //     // this.calFrame(frame, frameRate);
        //     cc.log("chooseScene 接收帧同步成功");
        //     cc.log(`匹配场景帧同步状态：${Global.room.roomInfo.frameSyncState}`)
        //     cc.director.loadScene("game_scene");
        // }

        Global.room.onStartFrameSync = (event: MGOBE.types.BroadcastEvent<MGOBE.types.StartFrameSyncBst>) => {
            if (this.isDisable) {
                return;
            }
            this.isDisable = true;

            cc.log("chooseScene 开始帧同步");
            cc.log(`匹配场景帧同步状态：${Global.room.roomInfo.frameSyncState}`)
            cc.director.loadScene("game_scene");
        }

    }

    update(dt) { }


    //进行匹配
    enterMatching() {
        this.label.string = "正在匹配...";
        //时间计时器
        this.matchTime = 0;
        clearInterval(this.timer);
        this.doTimer();
        this.timer = setInterval(this.doTimer.bind(this), 1000);

        this.startMatch();
    }

    doTimer(){
        if (this.matchTime == 0) {
            this.timeLabel.string = "";
        } else if (this.matchTime >= 15) {
            this.timeLabel.string = this.matchTime.toString();
            clearInterval(this.timer);
        } else {
            this.timeLabel.string = this.matchTime.toString();
        }
        this.matchTime += 1;
    }

    //开始匹配
    startMatch() {
        const playerInfo = {
            name: Global.userInfo.nickName,
            customPlayerStatus: 1,
            customProfile: Global.userInfo.avatarUrl,
            matchAttributes: [{
                name: "lv",
                value: 1,
            }]
        };
        const matchPlayersPara = {
            playerInfo: playerInfo,
            matchCode: Global.matchCode,
        };
        // 发起玩家匹配
        Global.room.matchPlayers(matchPlayersPara, event => {

            let res = event.code;
            console.log("匹配状态，" + res);
            // 已经在匹配中
            if (res === MGOBE.ErrCode.EC_MATCH_PLAYER_IS_IN_MATCH) {
                return;
            }

            // 已经在房间内
            if (res === MGOBE.ErrCode.EC_ROOM_PLAYER_ALREADY_IN_ROOM) {
                // TODO  暂时先离开房间，重新匹配
                Global.room.leaveRoom({}, (event) => {
                    if (event.code == MGOBE.ErrCode.EC_OK) {
                        this.enterMatching();
                    }
                });
                return;
                this.openGameScene();
            }

            // 匹配成功
            if (res === MGOBE.ErrCode.EC_OK) {
                clearInterval(this.timer);
                this.startFrame();
                return;
            }

            //匹配超时
            if (res === MGOBE.ErrCode.EC_MATCH_TIMEOUT) {
                this.matchTime = 15;
                this.doTimer();
                clearInterval(this.timer);
                Global.alert.show("超时未匹配到对手，请您重新匹配",
                    () => this.enterMatching(),
                    () => cc.director.loadScene("home_scene")
                );
                return;
            }
        });

    }

    //开始帧同步
    startFrame() {
        // 只有房主才能调用开始帧同步
        if (Global.room.roomInfo.owner !== MGOBE.Player.id) {
            return;
        }

        Global.room.startFrameSync({}, event => {
            if (event.code != MGOBE.ErrCode.EC_OK) {
                Global.alert.show("开始失败，是否尝试重新加载",
                    () => { this.startFrame(); },
                    () => { cc.director.loadScene("home_scene") });
                return;
            }
            cc.log("房主开始帧同步");
        });
    }



    //打开游戏场景
    openGameScene() {
        clearInterval(this.timer);
        cc.log("匹配成功,即将进入游戏");
        cc.log(Global.room.roomInfo);
        cc.director.loadScene("game_scene");
    }

    //取消匹配
    cancelMatching() {
        Global.room.cancelPlayerMatch({ matchType: MGOBE.ENUM.MatchType.PLAYER_COMPLEX }, event => {
            cc.log("取消匹配：" + event.code);
            clearInterval(this.timer);
            cc.director.loadScene("home_scene");
        });
    }

}
